package com.zone.mybatis.executor.statement;

import com.zone.mybatis.executor.resultset.ResultSetHandler;
import com.zone.mybatis.mapping.BoundSql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

/**
 * @author: zongzi
 * @description: TODO
 * @date: 2024/1/1
 */
public class PrepareStatementHandler extends BaseStatementHandler {
    private BoundSql boundSql;

    private Object params;

    private ResultSetHandler resultSetHandler;

    public PrepareStatementHandler(BoundSql boundSql, Object params, ResultSetHandler resultSetHandler) {
        this.boundSql = boundSql;
        this.params = params;
        this.resultSetHandler = resultSetHandler;
    }

    @Override
    public Statement instantiateStatement(Connection connection) throws SQLException {
        String sql = boundSql.getSql();
        return connection.prepareStatement(sql);
    }

    @Override
    public void parameterize(Statement statement) throws SQLException {
        PreparedStatement ps = (PreparedStatement) statement;
        Object[] args = (Object[]) params;
        Long id = (Long) args[0];
        ps.setLong(1, id);
    }

    @Override
    public <E> List<E> query(Statement statement) throws SQLException {
        PreparedStatement ps = (PreparedStatement) statement;
        ps.execute();
        return resultSetHandler.handleResultSet(ps);
    }
}
